package com.randy.recyclerviews.helper;

import com.randy.recyclerviews.modal.WithUniqueIdentity;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;

/**
 * Created by xudshen on 06/08/2017.
 */

public final class ItemModelFilter extends HashMap<Class, HashSet<Long>> {
    HashSet<Long> getFilter(Class clazz) {
        if (!containsKey(clazz)) {
            put(clazz, new HashSet<Long>());
        }
        return get(clazz);
    }

    public void doFilter(List<?> list) {
        Iterator<?> iterator = list.iterator();
        while (iterator.hasNext()) {
            Object object = iterator.next();
            if (WithUniqueIdentity.class.isInstance(object)) {
                WithUniqueIdentity identity = (WithUniqueIdentity) object;

                HashSet<Long> filter = getFilter(identity.getClazz());
                Long uniqueId = identity.uniqueId();

                if (uniqueId == -1 || filter.contains(uniqueId)) {
                    iterator.remove();
                } else {
                    filter.add(uniqueId);
                }
            } else {
                iterator.remove();
            }
        }
    }
}
